//
//  ConversationViewController.m
//  SeaChat
//
//  Created by 刘汉 on 16/6/18.
//  Copyright © 2016年 潘强. All rights reserved.
//

#import "ConversationViewController.h"
#import "ChatCell.h"

@interface ConversationViewController ()<UITableViewDataSource,UITableViewDelegate,UITextViewDelegate,EMChatManagerDelegate>

@property(nonatomic,retain)UITableView *tableV;

@property(nonatomic,retain)UIView *sendView;

@property(nonatomic,retain)UITextView *textInput;

@property(nonatomic,retain)NSMutableArray *dataArr;

@property(nonatomic,retain)ChatCell *cellTool;

@end

@implementation ConversationViewController



- (void)dealloc
{    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [_tableV release];
    [_textInput release];
    [_sendView release];
    [_dataArr release];
    [_cellTool release];
    [_userName release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"聊天";
    self.view.backgroundColor = [UIColor whiteColor];

    self.navigationItem.title = self.userName;

    self.dataArr =  [NSMutableArray array];


    [self creatToolBar];


    self.tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    [self.view addSubview:_tableV];
     [self.tableV makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(64);
         make.bottom.equalTo(self.sendView.top);
         make.width.equalTo(self.view);
     }];
    _tableV.keyboardDismissMode = YES;
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    UINib *nib = [UINib nibWithNibName:@"reveiceCell" bundle:[NSBundle mainBundle]];
    [self.tableV registerNib:nib forCellReuseIdentifier:resuse];
    UINib *nib2 = [UINib nibWithNibName:@"SenderCell" bundle:[NSBundle mainBundle]];
    [self.tableV registerNib:nib2 forCellReuseIdentifier:reuse2];

    self.cellTool = [self.tableV dequeueReusableCellWithIdentifier:resuse];
    [_tableV release];


    NSLog(@"%@",self.userName);
    //监听键盘的弹出,把输入的工具条往上移;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillshow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillhide:) name:UIKeyboardWillHideNotification object:nil];


    [self loadLocalChatRecords];

}
-(void)loadLocalChatRecords{

   EMConversation *coversation =   [[EMClient sharedClient].chatManager getConversation:self.userName type:EMConversationTypeChat createIfNotExist:YES];
    NSLog(@"%@",coversation);
    NSLog(@"%@",coversation.conversationId);
   NSArray *arr =[coversation loadMoreMessagesWithType:EMMessageBodyTypeText before:-1 limit:-1 from:[EMClient sharedClient].currentUsername direction:EMMessageSearchDirectionUp];
        NSLog(@"%@",arr);
    [self didReceiveMessages:arr];

}

- (void)didReceiveMessages:(NSArray *)aMessages
{


    for (EMMessage *message in aMessages) {
        EMMessageBody *msgBody = message.body;
        switch (msgBody.type) {
            case EMMessageBodyTypeText:
            {
                // 收到的文字消息
                EMTextMessageBody *textBody = (EMTextMessageBody *)msgBody;
                NSString *txt = textBody.text;
                [self.dataArr addObject:txt];
                NSLog(@"%ld",self.dataArr.count);

                NSLog(@"收到的文字是 txt -- %@",txt);
            }
                break;
            case EMMessageBodyTypeImage:
            {
                // 得到一个图片消息body
                EMImageMessageBody *body = ((EMImageMessageBody *)msgBody);
                NSLog(@"大图remote路径 -- %@"   ,body.remotePath);
                NSLog(@"大图local路径 -- %@"    ,body.localPath); // // 需要使用sdk提供的下载方法后才会存在
                NSLog(@"大图的secret -- %@"    ,body.secretKey);
                NSLog(@"大图的W -- %f ,大图的H -- %f",body.size.width,body.size.height);
                NSLog(@"大图的下载状态 -- %u",body.downloadStatus);


                // 缩略图sdk会自动下载
                NSLog(@"小图remote路径 -- %@"   ,body.thumbnailRemotePath);
                NSLog(@"小图local路径 -- %@"    ,body.thumbnailLocalPath);
                NSLog(@"小图的secret -- %@"    ,body.thumbnailSecretKey);
                NSLog(@"小图的W -- %f ,大图的H -- %f",body.thumbnailSize.width,body.thumbnailSize.height);
                NSLog(@"小图的下载状态 -- %u",body.thumbnailDownloadStatus);
            }
                break;
            case EMMessageBodyTypeLocation:
            {
                EMLocationMessageBody *body = (EMLocationMessageBody *)msgBody;
                NSLog(@"纬度-- %f",body.latitude);
                NSLog(@"经度-- %f",body.longitude);
                NSLog(@"地址-- %@",body.address);
            }
                break;
            case EMMessageBodyTypeVoice:
            {
                // 音频sdk会自动下载
                EMVoiceMessageBody *body = (EMVoiceMessageBody *)msgBody;
                NSLog(@"音频remote路径 -- %@"      ,body.remotePath);
                NSLog(@"音频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在（音频会自动调用）
                NSLog(@"音频的secret -- %@"        ,body.secretKey);
                NSLog(@"音频文件大小 -- %lld"       ,body.fileLength);
                NSLog(@"音频文件的下载状态 -- %u"   ,body.downloadStatus);
                NSLog(@"音频的时间长度 -- %d"      ,body.duration);
            }
                break;
            case EMMessageBodyTypeVideo:
            {
                EMVideoMessageBody *body = (EMVideoMessageBody *)msgBody;

                NSLog(@"视频remote路径 -- %@"      ,body.remotePath);
                NSLog(@"视频local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
                NSLog(@"视频的secret -- %@"        ,body.secretKey);
                NSLog(@"视频文件大小 -- %lld"       ,body.fileLength);
                NSLog(@"视频文件的下载状态 -- %u"   ,body.downloadStatus);
                NSLog(@"视频的时间长度 -- %d"      ,body.duration);
                NSLog(@"视频的W -- %f ,视频的H -- %f", body.thumbnailSize.width, body.thumbnailSize.height);

                // 缩略图sdk会自动下载
                NSLog(@"缩略图的remote路径 -- %@"     ,body.thumbnailRemotePath);
                NSLog(@"缩略图的local路径 -- %@"      ,body.thumbnailLocalPath);
                NSLog(@"缩略图的secret -- %@"        ,body.thumbnailSecretKey);
                NSLog(@"缩略图的下载状态 -- %u"      ,body.thumbnailDownloadStatus);
            }
                break;
            case EMMessageBodyTypeFile:
            {
                EMFileMessageBody *body = (EMFileMessageBody *)msgBody;
                NSLog(@"文件remote路径 -- %@"      ,body.remotePath);
                NSLog(@"文件local路径 -- %@"       ,body.localPath); // 需要使用sdk提供的下载方法后才会存在
                NSLog(@"文件的secret -- %@"        ,body.secretKey);
                NSLog(@"文件文件大小 -- %lld"       ,body.fileLength);
                NSLog(@"文件文件的下载状态 -- %u"   ,body.downloadStatus);
            }
                break;
                
            default:
                break;
        }
    }

   [self.tableV scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArr.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
}
#pragma mark UItextView代理

-(void)textViewDidChange:(UITextView *)textView{

    if ([textView.text hasSuffix:@"\n"]) {
        NSLog(@"发送操作");
        //清空textView的文字
        [self sendMessage:textView.text];

        textView.text = nil;

    }
  //监听send事件
}

-(void)sendMessage:(NSString *)text{


    EMTextMessageBody *body = [[EMTextMessageBody alloc]initWithText:text];
    NSString *from = [[EMClient sharedClient] currentUsername];
    EMMessage *message = [[EMMessage alloc] initWithConversationID:nil from:from to:self.userName body:body ext:nil];
    message.chatType = EMChatTypeChat;

[[EMClient sharedClient].chatManager asyncSendMessage:message progress:^(int progress) {
    NSLog(@"准备发送消息");


} completion:^(EMMessage *message, EMError *error) {
    NSLog(@"发送完成");

}];


}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    //设置toollabel的数据;
    self.cellTool.MessageLabel.text = self.dataArr[indexPath.row];

    return [self.cellTool CellHeight];

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    ChatCell *cell = nil;
    if (indexPath.row % 2 == 0) {
         cell = [tableView dequeueReusableCellWithIdentifier:resuse];
    }else{
         cell = [tableView dequeueReusableCellWithIdentifier:reuse2];
    }

    cell.MessageLabel.text = self.dataArr[indexPath.row];
    return  cell;
}

#pragma mark 键盘显示时触发的方法.


-(void)keyboardWillshow:(NSNotification *)noti{
//1.获取键盘的高度
    //1.1获取键盘结束时候的位置
    CGRect kbendFrm =    [noti.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat kbHeight = kbendFrm.size.height;
    //2更改sendView的高度
  [UIView animateWithDuration:0.25 animations:^{
    [self.sendView updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(-kbHeight);
    }];

      [self.view layoutIfNeeded];
}];

  }

-(void)keyboardWillhide:(NSNotification*)noti{

 [UIView animateWithDuration:0.25 animations:^{
     [self.sendView updateConstraints:^(MASConstraintMaker *make) {
         make.bottom.equalTo(0);
     }];
     [self.view layoutIfNeeded];
 }];


}

-(void)creatToolBar{


    self.sendView = [UIView new];
    [self.view addSubview:self.sendView];
    [self.sendView makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(0);
        make.height.equalTo(49);
        make.width.equalTo(self.view);

    }];
    [_sendView release];
    _sendView.backgroundColor = [UIColor lightGrayColor];

    UIButton *voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [voiceBtn setImage:[UIImage imageNamed:@"macChat" ]forState:UIControlStateNormal];
    [self.sendView addSubview:voiceBtn];
    [voiceBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(10);
        make.width.equalTo( 39);
        make.height.equalTo(self.sendView ).offset(-10);
        make.bottom.equalTo(self.sendView.bottom).offset(-5);

    }];
    UIButton *emoticon  = [UIButton buttonWithType:UIButtonTypeCustom];
    [emoticon setImage:[UIImage imageNamed:@"smileChat" ]forState:UIControlStateNormal];
    [self.sendView addSubview:emoticon];
    [emoticon makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(- 50);
        make.height.width.equalTo(voiceBtn);
        make.bottom.equalTo(voiceBtn.bottom);
    }];
    UIButton *AddBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [AddBtn setImage:[UIImage imageNamed:@"addChat" ]forState:UIControlStateNormal];
    [self.sendView addSubview:AddBtn];
    [AddBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(- 10);
        make.height.width.equalTo(voiceBtn);
        make.bottom.equalTo(voiceBtn.bottom);
    }];

    self.textInput = [UITextView new];
    [self.sendView addSubview:_textInput];
    [_textInput makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(voiceBtn.right).offset(5);
        make.right.equalTo(emoticon.left).offset(-5);
        make.height.equalTo(emoticon);
        make.bottom.equalTo(_sendView.bottom).offset(-5);
    }];
    _textInput.backgroundColor = [UIColor redColor];
    _textInput.delegate = self;
    _textInput.font = [UIFont systemFontOfSize:17];
    _textInput.returnKeyType = UIReturnKeySend;

}
@end
